use crate::modal::sys_user;
use axum::extract::Path;
use axum::response::IntoResponse;
use axum::routing::{get, post};
use axum::{Json, Router};
use serde_json::Value;
use void_log::*;
use crate::modal::sys_user::SysUser;
use crate::sys_controller::Info;

async fn user_list() -> impl IntoResponse {
    log_info!("user_list");
    let data = sys_user::list().await;
    let res = Info::data(0, "成功", Some(data));
    Json(res)
}

async fn user_select(Path(id): Path<i64>) -> impl IntoResponse {
    log_info!("user_select_{}", id);
    let data = sys_user::select(id).await;
    let res = Info::data(0, "成功", Some(data));
    Json(res)
}

async fn user_update(Json(request): Json<SysUser>) -> impl IntoResponse {
    log_info!("user_update");
    let data = sys_user::update(request).await;
    let mag = match data.rows_affected() {
        0 => { "无修改" }
        _ => { "修改成功" }
    };
    let res = Info::<()>::data(0, mag, None);
    Json(res)
}

async fn user_update_password(Json(request): Json<Value>) -> impl IntoResponse {
    log_info!("user_update");
    let id = request["id"].as_i64().unwrap();
    let new_pwd = request["new_password"].as_str().unwrap();
    let data = sys_user::update_password(id, new_pwd).await;
    let res = Info::<()>::data(0, data, None);
    Json(res)
}

pub async fn router(app_router: Router) -> Router {
    app_router
        .route("/system/user/list", get(user_list))
        .route("/system/user/:id", get(user_select))
        .route("/system/user", post(user_update))
        .route("/system/user/reset_pwd", post(user_update_password))
}